import React, { Component } from 'react';
import { connect } from 'react-redux'
import actions from '../../../store/actions';
import './style.css'

class Index extends Component {
  // 加入购物车
  addCarItem(v) {
    const { dispath } = this.props
    const action = actions.addCar(v)
    dispath(action)
  }
  // 减少购物车
  subCarItem(v) {
    const { dispath } = this.props
    const action = actions.subCar(v)
    dispath(action)
  }
  // 全选
  checkAll(checked) {
    const { dispath } = this.props
    const action = actions.allCheck({ checked })
    dispath(action)
  }
  // 单选
  checkOne(v) {
    const { dispath } = this.props
    const action = actions.oneCheck(v)
    dispath(action)
  }
  // 总价
  totalPrice() {
    const { car } = this.props
    let price = 0
    car.forEach(v => {
      if(v.checked)
        price += v.price * v.count
    })
    return price
  }
  render() {
    const { car } = this.props
    console.log(car);
    return (
      <div>
        {
          car.length > 0 && car.map((v, i) => {
            return (
              <div className="car-item"key={i}>
                {/* 受控组件 */}
                <input type="checkbox" checked={ v.checked } onChange={ () => this.checkOne(v) }/>
                <dl>
                  <dt><img src={v.url} alt="" /></dt>
                  <dd>
                    <h3>{v.title}</h3>
                    <h4>￥: {v.price} </h4>
                    <p>
                      <button onClick={ () => this.subCarItem(v) }>-</button>
                      <b>{v.count}</b>
                      <button onClick={ () => this.addCarItem(v) }>+</button>
                    </p>
                  </dd>
                </dl>
              </div>
            )
          })
        }

        <div className="footer" style={{
          position:'fixed',
          left:0,
          bottom:0,
          width: "100%",
          height: '6vh',
          display:'flex',
          justifyContent: 'space-around',
          alignItems: 'center',
          background: '#fff'
        }}>
          <div>
            {/* 受控 */}
          <input type="checkbox"  checked={ car.every(v => v.checked) } onChange={ (e) => this.checkAll(e.target.checked) }/>全选
          </div>
          <b>总价：{ this.totalPrice() }</b>
          <button>提交订单</button>
        </div>
      </div>
    );
  }
}

const mapState = state => {
  return {
    car: state.car
   }
}
const mapDiapatch = dispath => {
  return { dispath }
}

export default connect(mapState, mapDiapatch)(Index);
